package com.qdxwx.data.service.account;

import com.qdxwx.common.exception.AccountException;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.ObjectUtils;
import com.qdxwx.data.mapper.account.UserAccountDetailMapper;
import com.qdxwx.data.mapper.account.UserAccountMapper;
import com.qdxwx.data.mapper.account.UserAccountOptMapper;
import com.qdxwx.models.account.UserAccount;
import com.qdxwx.models.account.UserAccountDTO;
import com.qdxwx.models.account.UserAccountDetail;
import com.qdxwx.models.account.UserAccountOpt;
import com.qdxwx.models.enums.AccountBizType;
import com.qdxwx.models.enums.AccountHistoryType;
import com.qdxwx.models.enums.AccountStatus;
import com.qdxwx.models.enums.AccountType;
import com.qdxwx.models.manager.Manager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


/**
 * UserAccount接口
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Service
public class UserAccountServiceImpl implements UserAccountService {

	private final static Logger logger = LoggerFactory.getLogger(UserAccountServiceImpl.class);

	@Autowired
	private UserAccountMapper userAccountMapper;
	@Autowired
	private UserAccountDetailMapper userAccountDetailMapper;
	@Autowired
	private UserAccountOptMapper userAccountOptMapper;

	/**
	 * 添加UserAccount
	 */
	@Override
	public void insert(UserAccount userAccount) {
		userAccount.setCreateTime(LocalDateTime.now());
		userAccount.setUpdateTime(LocalDateTime.now());
		userAccountMapper.createUserAccount(userAccount);
	}

	/**
	 * 根据id获取单个UserAccount对象
	 *
	 * @param userId 要查询的id
	 * @return UserAccount
	 */
	@Override
	public UserAccount getByUserId(long userId) throws AccountException {
		if (userId < 1) {
			return null;
		}
		UserAccount account = userAccountMapper.getUserAccountByUserId(userId);
		if (ObjectUtils.isNull(account)) {
			account = new UserAccount();
			account.setUserId(userId);
			account.setBalance(0);
			account.setBackAmount(0);
			account.setVmAmount(0);
			account.setFrozenAmount(0);
			account.setAccountStatus(AccountStatus.ACTIVE.toString());
			insert(account);
			//throw new AccountException(AccountException.ACCOUNT_NOT_FOUND);// 账户不存在
		}
		return account;
	}

	/**
	 * 根据用户id获得详情
	 */
	@Override
	public UserAccountDTO getDTOByUserId(long userId) {
		return userAccountMapper.getUserAccountInfo(userId);
	}

	// 扣款,消费操作
	@Override
	@Transactional(rollbackFor = Exception.class)
	public UserAccount deduct(UserAccount account, int amount, AccountHistoryType accountHistoryType, int orderId,
							  String description, boolean isDisplay, AccountBizType accountBizType) throws AccountException {
		if (account == null || amount <= 0) {
			return account;
		}
		try {
			account.debit(amount);// 扣除操作,cash,vm具体在此方法中
		} catch (IllegalArgumentException e) {
			throw new AccountException(e.getMessage());
		}
		// 更新账户dao
		account.setUpdateTime(LocalDateTime.now());
		userAccountMapper.updateUserAccount(account);
		// 添加账户历史操作记录
		UserAccountDetail userAccountDetail = new UserAccountDetail();
		userAccountDetail.setUserId(account.getUserId());
		userAccountDetail.setOrderId(orderId);// 订单id
		if (isDisplay) {// 是否显示账户历史记录:0显示;1不显示
			userAccountDetail.setIsDisplay(0);
		} else {
			userAccountDetail.setIsDisplay(1);
		}
		userAccountDetail.setBalance(account.getBalance());// 当前余额
		userAccountDetail.setVmAmount(account.getVmAmount());// vm余额
		userAccountDetail.setBackAmount(account.getBackAmount());// 提现余额
		userAccountDetail.setOrderAmount(amount);// 交易金额
		userAccountDetail.setDescription(description);// 账户历史内容描述
		userAccountDetail.setActHistoryType(accountHistoryType.toString());// 帐务历史类型.充值。消费等
		userAccountDetail.setBizType(accountBizType.toString());// 业务类型(课程订单、会员订单、图书订单，音频课程)
		userAccountDetail.setVersion(account.getVersion());// 乐观锁版本号
		userAccountDetail.setCreateTime(LocalDateTime.now());
		userAccountDetailMapper.insertUserAccountDetail(userAccountDetail);
		logger.info("debit SUCCESS:balance:" + account.getBalance() + ";orderAmount:" + amount + "");
		return account;
	}

	/**
	 * 账户入账,充值 入款
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public UserAccount income(UserAccount account, int amount, AccountType accountType, AccountHistoryType accountHistoryType, int orderId,
							  String description, boolean isDisplay, AccountBizType accountBizType) throws AccountException {
		if (account == null || amount <= 0) {
			return account;
		}
		account.credit(amount, accountType);//入款 根据入款金额 和 入款类型 计算
		// 更新账户dao
		account.setUpdateTime(LocalDateTime.now());
		userAccountMapper.updateUserAccount(account);
		// 添加账户历史操作记录
		UserAccountDetail accountHistory = new UserAccountDetail();
		accountHistory.setUserId(account.getUserId());
		accountHistory.setOrderId(orderId);// 订单id
		if (isDisplay) {// 是否显示账户历史记录:0显示;1不显示
			accountHistory.setIsDisplay(0);
		} else {
			accountHistory.setIsDisplay(1);
		}
		accountHistory.setBalance(account.getBalance());// 当前余额
		accountHistory.setVmAmount(account.getVmAmount());// vm余额
		accountHistory.setBackAmount(account.getBackAmount());// 提现余额
		accountHistory.setOrderAmount(amount);// 交易金额
		accountHistory.setDescription(description);// 账户历史内容描述
		accountHistory.setActHistoryType(accountHistoryType.toString());// 帐务历史类型.充值。消费等
		accountHistory.setBizType(accountBizType.toString());// 业务类型(课程订单、会员订单、图书订单)
		accountHistory.setVersion(account.getVersion());// 乐观锁版本号
		accountHistory.setCreateTime(LocalDateTime.now());
		userAccountDetailMapper.insertUserAccountDetail(accountHistory);
		return account;
	}

	@Override
	public int update(UserAccount userAccount) {
		userAccount.setUpdateTime(LocalDateTime.now());
		return userAccountMapper.updateUserAccount(userAccount);
	}

	@Override
	public List<UserAccountDTO> getList(UserAccountDTO account, PageRequest page) {
		return userAccountMapper.selectDtoList(account, page);
	}

	@Override
	public long count(UserAccountDTO account) {
		return userAccountMapper.selectDtoCount(account);
	}

	@Override
	public void deleteByIds(String[] idsArr) {
		userAccountMapper.deleteUserAccountByIds(idsArr);
	}

	@Override
	public int delete(long userId) {
		return userAccountMapper.deleteById(userId);
	}
	/**
	 * 添加账户操作记录
	 */
	@Override
	public void addUserAccountOpt(long userId, Manager manager, int amount, String type, String outNo) {
		UserAccountOpt userAccountOpt = new UserAccountOpt();
		userAccountOpt.setUserId(userId);//用户Id
		userAccountOpt.setManagerId(manager.getManagerId());//操作人id
		userAccountOpt.setManagerName(manager.getLoginName());//操作人名字
		userAccountOpt.setAmount(amount);//操作金额
		userAccountOpt.setType(type);// 操作类型
		userAccountOpt.setOutNo(outNo);//操作标示
		if (type.equalsIgnoreCase(AccountHistoryType.ADMINLOAD.toString())) {//描述
			userAccountOpt.setDescription("后台充值");
		} else {
			userAccountOpt.setDescription("后台扣款");
		}
		userAccountOpt.setCreateTime(LocalDateTime.now());
		userAccountOptMapper.insertUserAccountOpt(userAccountOpt);
	}

	@Override
	public int updateCombine(long userId, UserAccount userAccount) {
		if(userId < 1 || userAccount == null){
			throw new RuntimeException("账户合并：参数错误");
		}
		return userAccountMapper.updateCombine(userId, userAccount);
	}
}